<!-- src/views/admin/OrderListView.vue -->
<template>
  <div class="order-list-page">
    <!-- 顶部导航栏 -->
    <TopNav />

    <div class="order-list-container">
      <div class="header-section">
        <h1>订单管理</h1>
        <div class="sort-controls">
          <span class="sort-label">排序方式：</span>
          <el-select v-model="sortOrder" @change="handleSortChange" size="small" class="sort-select">
            <el-option label="最新订单在前" value="desc"></el-option>
            <el-option label="最早订单在前" value="asc"></el-option>
          </el-select>
        </div>
      </div>

      <div class="order-list-content" ref="orderListContent">
        <div 
          class="order-item" 
          v-for="order in sortedOrders" 
          :key="order.id"
          @click="viewOrder(order)"
          :class="{ 'completed': order.status === 'completed' }"
        >
          <div class="order-header">
            <div class="order-id">订单编号: {{ order.id }}</div>
            <div class="order-date">{{ order.date }}</div>
          </div>
          <div class="order-body">
            <div class="order-items-preview">
              <div 
                class="item-preview" 
                v-for="(item, index) in order.items.slice(0, 3)" 
                :key="index"
              >
                <img :src="item.gImage" :alt="item.gName" class="item-image" />
              </div>
              <div class="item-more" v-if="order.items.length > 3">
                +{{ order.items.length - 3 }}
              </div>
            </div>
            <div class="order-summary">
              <div class="item-count">{{ order.items.length }} 件商品</div>
              <div class="order-total">￥{{ order.total.toFixed(2) }}</div>
              <div class="order-status" :class="order.status === 'completed' ? 'status-completed' : 'status-pending'">
                {{ order.status === 'completed' ? '已完成' : '未完成' }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="empty-orders" v-if="sortedOrders.length === 0">
        <p>暂无订单记录</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, watch, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import TopNav from '@/components/TopNav.vue'

const store = useStore()
const router = useRouter()

// 排序方式，默认为降序（最新在前）
const sortOrder = ref('desc')
const scrollPosition = ref(0)

// 订单列表内容区域的引用
const orderListContent = ref(null)

// 获取订单列表
const orders = computed(() => store.getters.getAdminOrders)

// 排序后的订单列表（未完成在前，已完成在后）
const sortedOrders = computed(() => {
  // 创建订单数组副本以避免修改原始数据
  const ordersCopy = [...orders.value]
  
  // 首先按状态排序：未完成在前，已完成在后
  ordersCopy.sort((a, b) => {
    // 如果一个是已完成，一个是未完成，则未完成的在前
    if (a.status === 'completed' && b.status !== 'completed') {
      return 1
    }
    if (a.status !== 'completed' && b.status === 'completed') {
      return -1
    }
    
    // 如果状态相同，则按时间排序
    const dateA = new Date(a.date).getTime()
    const dateB = new Date(b.date).getTime()
    
    if (sortOrder.value === 'asc') {
      // 升序排列（最早在前）
      return dateA - dateB
    } else {
      // 降序排列（最新在前）
      return dateB - dateA
    }
  })
  
  return ordersCopy
})

// 处理排序方式变化
const handleSortChange = (value) => {
  sortOrder.value = value
  // 保存排序偏好到 localStorage
  localStorage.setItem('adminOrderSortPreference', value)
}

// 查看订单详情
const viewOrder = (order) => {
  // 保存滚动位置
  if (orderListContent.value) {
    scrollPosition.value = orderListContent.value.scrollTop
  }
  
  // 保存当前查看的订单到 store
  store.commit('SET_CURRENT_ORDER', order)
  router.push('/orders/detail')
}

// 监听路由变化，恢复滚动位置
const afterEachHandler = (to, from) => {
  if (from.name === 'admin-orders-detail' && to.name === 'admin-orders-list') {
    // 使用 setTimeout 确保 DOM 已更新
    setTimeout(() => {
      if (orderListContent.value) {
        orderListContent.value.scrollTop = scrollPosition.value
      }
    }, 100)
  }
}

// 组件挂载时
onMounted(() => {
  // 从 localStorage 恢复排序偏好
  const savedSortPreference = localStorage.getItem('adminOrderSortPreference')
  if (savedSortPreference) {
    sortOrder.value = savedSortPreference
  }
  
  // 添加路由守卫
  router.afterEach(afterEachHandler)
  
  // 加载订单数据
  store.dispatch('loadAdminOrders')
})

// 组件卸载前
onBeforeUnmount(() => {
  // 移除路由守卫
  router.afterEach(afterEachHandler)
})
</script>

<style scoped>
.order-list-page {
  max-width: 1200px;
  margin: 60px auto;
  padding: 20px;
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
}

.order-list-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header-section h1 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.sort-controls {
  display: flex;
  align-items: center;
}

.sort-label {
  margin-right: 10px;
  color: #666;
}

.sort-select {
  width: 150px;
}

.order-list-content {
  max-height: 600px;
  overflow-y: auto;
}

.order-item {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.order-item:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.order-item.completed {
  background-color: #f9f9f9;
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.order-id {
  font-weight: bold;
  color: #333;
}

.order-date {
  color: #999;
}

.order-body {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-items-preview {
  display: flex;
  align-items: center;
}

.item-preview {
  width: 50px;
  height: 50px;
  margin-right: 10px;
  border-radius: 4px;
  overflow: hidden;
}

.item-preview .item-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-more {
  width: 50px;
  height: 50px;
  background-color: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 14px;
}

.order-summary {
  text-align: right;
}

.item-count {
  color: #999;
  margin-bottom: 5px;
}

.order-total {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.order-status {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.status-pending {
  color: #e6a23c;
  background-color: #fdf6ec;
}

.status-completed {
  color: #67c23a;
  background-color: #f0f9ec;
}

.empty-orders {
  text-align: center;
  padding: 60px 0;
}

.empty-orders p {
  font-size: 18px;
  color: #666;
  margin-bottom: 20px;
}

.go-shopping {
  display: inline-block;
  padding: 10px 20px;
  background-color: #4caf50;
  color: white;
  border-radius: 4px;
  text-decoration: none;
  font-size: 16px;
  transition: background-color 0.3s;
}

.go-shopping:hover {
  background-color: #45a049;
}
</style>